/*
 * Copyright (c) 2006-2010, Petr Panteleyev <petr@panteleyev.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.panteleyev.livejournal;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.MatchResult;

import org.panteleyev.ljapi.LJAccount;
import org.panteleyev.ljapi.LJEvent;
import org.panteleyev.ljapi.LJProperties;
import org.panteleyev.ljapi.LJUserpic;
import org.panteleyev.utilities.function.UnaryFunction;

/**
 *
 * @author Petr Panteleyev <petr@panteleyev.org>
 */
final class Previewer {
    private static final String REPOST_PATTERN =
        "<[Ll][Jj]-[Rr][Ee][Pp][Oo][Ss][Tt](\\s+[Bb][Uu][Tt][Tt][Oo][Nn]\\s*=\\s*\"(\\w*)\")?\\s*/?>((\\w*)</[Ll][Jj]-[Rr][Ee][Pp][Oo][Ss][Tt]>)?";
    private static final int REPOST_PATTERN_BUTTON = 2;

    private static final String LJ_USER_PATTERN =
        "<[Ll][Jj][Rr]?\\s+[Uu][Ss][Ee][Rr]\\s*=\\s*\"(\\w*)\"\\s*([Tt][Ii][Tt][Ll][Ee]\\s*=\\s*\"(.*)\"\\s*)?>";
    private static final String LJ_COMM_PATTERN =
        "<[Ll][Jj][Rr]?\\s+[Cc][Oo][Mm][Mm]\\s*=\\s*\"(\\w*)\"\\s*([Tt][Ii][Tt][Ll][Ee]\\s*=\\s*\"(.*)\"\\s*)?>";
    private static final int LJ_USER_PATTERN_NAME = 1;
    private static final int LJ_USER_PATTERN_TITLE = 3;

    private class RefFunction implements UnaryFunction<String, MatchResult> {
        private boolean comm;

        RefFunction(boolean comm) {
            this.comm = comm;
        }

        @Override
        public String call(MatchResult r) throws Exception {
            return buildUserReference(r.group(LJ_USER_PATTERN_NAME), r.group(LJ_USER_PATTERN_TITLE), comm);
        }
    };

    private RefFunction userRefFunction = new RefFunction(false);
    private RefFunction commRefFunction = new RefFunction(true);

    private final LJAccount account;
    private StringBuilder m_fullText;
    private StringBuilder m_cutText;

    private File m_fullFile;
    private File m_cutFile;
    private String m_fullFileName;

    public URL getCutFileURL() throws MalformedURLException {
        return m_cutFile.toURI().toURL();
    }
    public URL getFullFileURL() throws MalformedURLException {
        return m_fullFile.toURI().toURL();
    }

    /** Creates a new instance of Previewer */
    public Previewer(LJAccount account, LJEvent post) throws IOException {
        this.account = account;

        /* Open temporary files */
        m_fullFile = File.createTempFile("ljw", ".htm");
        m_fullFile.deleteOnExit();
        m_fullFileName = m_fullFile.toURI().toURL().toString();
        m_cutFile = File.createTempFile("ljw", ".htm");
        m_cutFile.deleteOnExit();

        /* Parse subject line */
        final StringBuilder subjectText = new StringBuilder(post.getSubject());
        handleLJTag(subjectText, LJ_USER_PATTERN, userRefFunction);
        handleLJTag(subjectText, LJ_COMM_PATTERN, commRefFunction);

        final StringBuilder textBuffer = new StringBuilder(post.getBody());

        handleLJTag(textBuffer, REPOST_PATTERN, new UnaryFunction<String, MatchResult>() {
            @Override
            public String call(MatchResult r) throws Exception {
                final String buttonText = r.group(REPOST_PATTERN_BUTTON);
                return new StringBuilder("<button>")
                    .append((buttonText != null)? buttonText : "Post this to your journal!")
                    .append("</button>")
                    .toString();
            }
        });

        handleLJTag(textBuffer, LJ_USER_PATTERN, userRefFunction);
        handleLJTag(textBuffer, LJ_COMM_PATTERN, commRefFunction);

        handleLJRaw(textBuffer);

        m_fullText = new StringBuilder("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">")
            .append("<style type=\"text/css\">\n")
            .append("a { text-decoration: none; }\n")
            .append("body,table,tr,td,form {font-size: 12pt; font-family: Verdana,Verdana,Tahoma,Arial,sans-serif;}")
            .append("</style>")
            .append("</head>")
            .append("<body vlink=\"#500050\" text=\"#000000\" bgcolor=\"#FFFFFF\" alink=\"#FF00C0\" link=\"#000050\" style=\"WORD-WRAP: break-word\">")
            .append("<table border='0'><tr>");

        String upicKey = post.getUserpic();
        if (upicKey == null) {
            upicKey = "(default)";
        }
        final LJUserpic upic = account.getUserpicByKey(upicKey);
        if (upic != null) {
            m_fullText.append("<td><img src='").append(upic.getUrl()).append("'>");
        }

        m_fullText.append("<td>")
            .append(account.getFullName())
            .append(" (")
            .append(buildUserReference(account.getLoginName(), account.getLoginName(), false))
            .append(") wrote on<br>")
            .append(post.getDate().toString())
            .append("</table><p><p>")
            /* Show subject */
            .append("<font color='blue'><b>")
            .append(subjectText.toString())
            .append("</b></font>")
            .append("<p>")
            /* Show the main body */
            .append(textBuffer.toString().replace("\n", "<br>"))
            .append("</body></html>");

///        this.m_cutText = new StringBuffer(m_fullText);
///        handleLJCuts(m_cutText);
        handleLJCuts();

        PrintWriter pr = new PrintWriter(m_cutFile, "UTF-8");
        pr.print(m_cutText);
        pr.close();

        pr = new PrintWriter(m_fullFile, "UTF-8");
        pr.print(m_fullText);
        pr.close();
    }

    private String extractValue(String tag) {
        int start = tag.indexOf('\"');
        if (start == -1) {
            return null;
        }
        int end = tag.indexOf('\"', start + 1);
        if (end == -1) {
            return null;
        }
        return tag.substring(start + 1, end);
    }

    private void handleLJTag(StringBuilder b, String regExp, UnaryFunction<String,MatchResult> repFunction) {
        int adj = 0;
        final Scanner scanner = new Scanner(b.toString());

        while (true) {
            final String found = scanner.findWithinHorizon(regExp, 0);
            if (found == null) {
                break;
            } else {
                MatchResult result = scanner.match();
                try {
                    String rep = repFunction.call(result);
                    b.replace(result.start() + adj, result.end() + adj, rep);
                    adj += rep.length() - found.length();
                } catch (Exception ex) {
                    break;
                }
            }
        }
    }

    private String buildUserReference(String userName, String userTitle, boolean comm) {
        final LJProperties props = account.getProperties();
        return new StringBuilder("<span class='ljuser' style='white-space: nowrap;'><a href='")
            .append(props.getUserInfoURL(userName))
            .append("'><img src='")
            .append((comm)? props.getCommInfoPictURL() : props.getUserInfoPictURL())
            .append("' ")
            .append("alt='[info]' width='17' height='17' border='0' valign='middle'></a><a href='")
            .append(props.getServerURL())
            .append("users/")
            .append(userName)
            .append("'><b>")
            .append((userTitle == null)? userName : userTitle)
            .append("</b></a></span>")
            .toString();
    }

    private void handleLJCuts() {
        m_cutText = new StringBuilder();

        int posStart = 0;
        int appendFrom = 0;
        int cutIndex = 0;

        while ((posStart = m_fullText.indexOf("<lj-cut", posStart)) != -1) {
            int tagEndPos = m_fullText.indexOf(">", posStart);
            if (tagEndPos == -1) {
                // TODO: Insert syntax exception here
                break;
            }

            // append text before tag to cutText
            m_cutText.append(m_fullText.substring(appendFrom, posStart));

            String cutTitle = "Read more";
            String tag = m_fullText.substring(posStart, tagEndPos + 1);
            if (tag.matches("<lj-cut\\s*text\\s*=\\s*\"[\\p{L}\\s\\d\\p{Punct}]*\"\\s*>")) {
                cutTitle = extractValue(tag);
            }

            String anchor = "#ljcut" + Integer.toString(cutIndex);

            // Form anchor text for full text
            StringBuilder anchorText = new StringBuilder("<a name='")
                .append(anchor)
                .append("'>");

            // replace starting tag by anchor
            m_fullText.replace(posStart, tagEndPos + 1, anchorText.toString());

            int endTagStart = m_fullText.indexOf("</lj-cut>", posStart);
            int posEnd = -1;
            if (endTagStart == -1) {
                endTagStart = m_fullText.length();
                posEnd = m_fullText.length();
            }

            if (posEnd != m_fullText.length()) {
                posEnd = endTagStart + 9;
            }

            // Remove </lj-cut>
            m_fullText.replace(endTagStart, posEnd, "");
            posEnd = endTagStart;


            m_cutText.append("<a href=\"")
                .append(m_fullFileName)
                .append(anchor)
                .append("\">( ")
                .append(cutTitle)
                .append(" )</a>");


            posStart = posEnd;
            appendFrom = posStart;

            cutIndex++;
        }

        // Add the rest of the text
        m_cutText.append(m_fullText.substring(appendFrom, m_fullText.length()));
    }

    private void handleLJRaw(StringBuilder b) {
        int posStart = 0;
        int posEnd;

        while (true) {
            posStart = b.indexOf("<lj-raw>", posStart);
            if (posStart == -1) {
                break;
            }

            posEnd = b.indexOf("</lj-raw>", posStart);
            if (posEnd == -1) {
                posEnd = b.length();
            }

            String sub = b.substring(posStart + 8, posEnd - 1);
            sub = sub.replaceAll("[\r\n]", "");
            if (posEnd != b.length()) {
                posEnd += 9;
            }

            b.replace(posStart, posEnd, sub);
        }
    }

}
